package com.siki.salessystemoauth2server.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siki.salessystemcommon.entity.Permission;
import com.siki.salessystemcommon.entity.Role;
import com.siki.salessystemcommon.entity.User;
import com.siki.salessystemcommon.mapper.PermissionMapper;
import com.siki.salessystemcommon.mapper.RoleMapper;
import com.siki.salessystemcommon.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义UserDetailService
 *
 * @Author Siki
 * @Date 2020/12/4
 */

//@Service("userDetailService")
@Service
@RequiredArgsConstructor
public class MyUserDetailService implements UserDetailsService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final PermissionMapper permissionMapper;

    // 可用性 :true:可用 false:不可用
    boolean enabled = true;
    // 过期性 :true:没过期 false:过期
    boolean accountNonExpired = true;
    // 有效性 :true:凭证有效 false:凭证无效
    boolean credentialsNonExpired = true;
    // 锁定性 :true:未锁定 false:已锁定
    boolean accountNonLocked = true;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据传入username查出用户信息, 并获取权限
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("account", username);
        User member = userMapper.selectOne(userQw);

        if (member == null) {
            throw new UsernameNotFoundException(username);
        }

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        List<Role> roles = roleMapper.selectRoleByUserId(member.getId());
        List<Long> roleIds = new ArrayList<Long>();
        for (Role role : roles) {
            // 角色必须是ROLE_开头，可以在数据库中设置
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
            grantedAuthorities.add(grantedAuthority);
            // 获取权限
            List<Permission> permissions = permissionMapper.selectPermissionByRoleId(role.getId());
            for (Permission p:permissions) {
                GrantedAuthority authority = new SimpleGrantedAuthority(p.getPermissionName());
                grantedAuthorities.add(authority);
            }
        }
        return new org.springframework.security.core.userdetails.User(member.getId(), member.getPassword(), grantedAuthorities);

    }
}
